package 线程安全.多线程;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;

public class SendMsg implements Runnable {
    private LinkedList<String> msgList = new LinkedList<>();
    private Socket socket;

    public SendMsg(Socket socket) {
        this.socket = socket;
    }

    public void addMsg(String msg) {
        msgList.add(msg);
    }

    @Override
    public void run() {
        System.out.println("发送进程启动！");
        try {
            BufferedOutputStream outputStream = new BufferedOutputStream(socket.getOutputStream());
            while (true) {
                Thread.sleep(1000);
                if (msgList.size() > 0) {
                    System.out.println("发送数据:" + msgList.getFirst());
                    outputStream.write(msgList.getFirst().toString().getBytes());
                    outputStream.flush();
                    msgList.removeFirst();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
